<template>
  <div class="todo-container">
    <div class="todo-block">
        <Header :addTodo="addTodo"></Header>
        <List :todos="todos" :updateTodo="updateTodo" :deleteTodo="deleteTodo"></List>
        <Footer :todos="todos" :checkAll="checkAll" :clearAllCompletedTodos="clearAllCompletedTodos"></Footer>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch } from 'vue';

// 引入组件
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import List from '@/components/List.vue'

// 引入接口
import { ITodo } from '@/types/todo'

export default defineComponent({
    name: 'Home',
    // 注册组件
    components: {
        Header,
        List,
        Footer,
    },
    setup() {
        const state = reactive<{todos: ITodo[]}>({
            todos: []
        })

        // 页面加载时判断一下local中是否有数据，有则从local中读取数据
        const data = localStorage.getItem('todos')
        if(data) {
            state.todos = JSON.parse(data)
        }

        // 所有对数据的操作方法声明都在home组件中，具体的调用在子组件中
        // 添加数据的方法
        const addTodo = (todo: ITodo) => {
            state.todos.unshift(todo); // 添加到顶部
        }

        // 删除数据的方法
        const deleteTodo = (index: number) => {
            state.todos.splice(index, 1)
        }

        // 修改isCompleted状态
        const updateTodo = (todo: ITodo, isCompleted: boolean) => {
            todo.isCompleted = isCompleted
        }

        // 全选或者全不选
        const checkAll = (isCompleted: boolean) => {
            state.todos.forEach(todo => {
                todo.isCompleted = isCompleted
            })
        }

        // 清理所有选中的数据
        const clearAllCompletedTodos = () => {
            state.todos = state.todos.filter(todo => !todo.isCompleted)
        }

        // 监视数据变化，所有变化后的数据都会存到local中
        watch(() => state.todos, () => {
            // 存到local中
            localStorage.setItem('todos', JSON.stringify(state.todos))
        }, {deep: true})

        return {
            ...toRefs(state),
            addTodo,
            deleteTodo,
            updateTodo,
            checkAll,
            clearAllCompletedTodos,
        }
    }
})

</script>

<style scoped lang="scss">
.todo-container {
    width: 500px;
    margin: 0 auto;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;

    .todo-block {
        display: flex;
        flex-wrap: wrap;
    }
}
</style>